const express = require('express')
const { nanoid } = require('nanoid')
const { getUserInfo } = require('../utils/permission')
const User = require('../models/User')
const router = express.Router()

/**
 * 提交订单信息
 */
router.post('/', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    /* 从请求中获取添加的订单数据 */
    const order = req.body

    User.find({ phone: user?.phone }, 'orders').then(data => {
      const orders = data[0]?.orders ?? []
      order.id = nanoid() // 订单号
      order.createdAt = Date.now() // 下单时间
      order.status = 1 // 1: 提交订单  2: 买家已付款  3: 卖家已发货  4. 买家已收货(交易成功)
      orders.push(order)
      User.updateOne({ phone: user.phone }, { orders }).then(() => {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '订单提交成功',
            id: order.id,
          },
        })
      })
    })
  } else {
    res.json({
      code: 200,
      data: {
        status: 400,
        message: '没有用户信息',
      },
    })
  }
})

/**
 * 订单支付
 */
router.post('/:id/pay', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    const { id } = req.params
    const { method } = req.body

    User.find({ phone: user?.phone }, 'orders').then(data => {
      const orders = data[0]?.orders
      const order = orders?.find(order => order.id === id) ?? {}
      order.payedAt = Date.now()
      order.paymentMethod = method // 支付方式
      order.status = 2 // 1: 提交订单  2: 买家已付款  3: 卖家已发货  4. 买家已收货(交易成功)
      User.updateOne({ phone: user.phone }, { orders }).then(() => {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '订单支付成功',
          },
        })
      })
    })
  } else {
    res.json({
      code: 200,
      data: {
        status: 400,
        message: '没有用户信息',
      },
    })
  }
})

/**
 * 买家收货，订单完成
 */
router.post('/:id/accept', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    const { id } = req.params

    User.find({ phone: user?.phone }, 'orders').then(data => {
      const orders = data[0]?.orders
      const order = orders?.find(order => order.id === id) ?? {}
      order.finishedAt = Date.now()
      order.status = 4 // 1: 提交订单  2: 买家已付款  3: 卖家已发货  4. 买家已收货(交易成功)
      User.updateOne({ phone: user.phone }, { orders }).then(() => {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '交易完成',
          },
        })
      })
    })
  } else {
    res.json({
      code: 200,
      data: {
        status: 400,
        message: '没有用户信息',
      },
    })
  }
})

// /**
//  * 修改订单状态信息
//  */
// router.put('/:id', (req, res) => {
//   const user = getUserInfo(req)
//   if (user) {
//     const { id } = req.params
//     const { order } = req.body

//     User
//       .find({phone: user?.phone}, 'orders')
//       .then(data => {
//         const orders = data[0]?.orders ?? []

//         const result = orders.map(orderItem => {
//           const copy = { ...orderItem }
//           if (copy.id === id) {
//             return {id, ...order}
//           }
//           return copy
//         })

//         User
//           .updateOne({phone: user.phone}, { orders: result })
//           .then(() => {
//             res.json({
//               code: 200,
//               data: {
//                 status: 200,
//                 message: '更新成功'
//               }
//             })
//           })
//       })
//   } else {
//     res.json({
//       code: 200,
//       data: {
//         message: '没有用户信息'
//       }
//     })
//   }
// })

/**
 * 删除订单
 */
router.delete('/:id', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    const { id } = req.params

    User.find({ phone: user?.phone }, 'orders').then(data => {
      const orders = data[0]?.orders ?? []
      const order = orders?.find(order => order.id === id) ?? {}
      order.status = -1 // -1: 删除订单  1: 提交订单  2: 买家已付款  3: 卖家已发货  4. 买家已收货(交易成功)

      User.updateOne({ phone: user.phone }, { orders }).then(() => {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '删除成功',
          },
        })
      })
    })
  } else {
    res.json({
      code: 200,
      data: {
        message: '没有用户信息',
      },
    })
  }
})

/**
 * 查询订单详情
 */
router.get('/:id', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    const { id } = req.params

    User.find({ phone: user?.phone }, 'orders').then(data => {
      const order = (data[0]?.orders ?? []).find(order => order.id === id)

      res.json({
        code: 200,
        data: {
          status: 200,
          order,
          message: '查询成功',
        },
      })
    })
  } else {
    res.json({
      code: 200,
      data: {
        message: '没有用户信息',
      },
    })
  }
})

/**
 * 查询订单列表
 */
router.get('/', (req, res) => {
  const user = getUserInfo(req)
  if (user) {
    const { start = 0, status = 0 } = req.query

    User.find({ phone: user?.phone }, 'orders')
      .sort('-createdAt')
      .then(data => {
        let orders = data[0]?.orders ?? []
        console.log('原始', orders, status)
        orders = orders.filter(order => {
          const _status = Number(status)
          if (_status === 4) {
            return order.status === 4
          }
          if (_status >= 2) {
            return order.status >= 2 && order.status < 4
          }
          if (_status === 1) {
            return order.status === 1
          }
          return order.status !== -1
        })
        console.log('等待:', orders)
        const total = orders.length
        orders = orders.slice(start, Number(start) + 10)
        console.log('等待2:', orders)

        res.json({
          code: 200,
          data: {
            list: orders,
            isEnd: Number(start) + 10 >= total,
            nextIndex: Number(start) + 10,
          },
        })
      })
  } else {
    res.json({
      code: 200,
      data: {
        message: '没有用户信息',
      },
    })
  }
})

module.exports = router
